package util;

import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @author xiongyx
 * @date 2020/5/14
 *
 * 图片工具类
 */
@Slf4j
public class PictureUtil {

    private static final int KB_SIZE = 1024;


    /**
     * 根据指定大小压缩图片
     *
     * @param imageBytes  源图片字节数组
     * @param desFileSize 指定图片大小，单位kb
     * @return 压缩质量后的图片字节数组
     */
    public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize) {
        return compressPicForScale(imageBytes,desFileSize,"");
    }

    /**
     * 根据指定大小压缩图片
     *
     * @param imageBytes  源图片字节数组
     * @param desFileSize 指定图片大小，单位kb
     * @param imageId     影像编号
     * @return 压缩质量后的图片字节数组
     */
    public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize, String imageId) {
        if(imageBytes == null){
            log.info("imageBytes is null");
            return null;
        }

        long imageByteLength = imageBytes.length;
        long limit = desFileSize * KB_SIZE;
        if (imageByteLength <= 0 || imageByteLength < limit) {
            log.info("当前图片大小 imageBytes.length=>{},desFileSize=>{}kb, 不需要进行压缩",imageByteLength,desFileSize);
            return imageBytes;
        }

        long srcSize = imageBytes.length;
        double accuracy = getAccuracy(srcSize / KB_SIZE);
        try {
            while (imageBytes.length > desFileSize * KB_SIZE) {
                ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
                Thumbnails.of(inputStream)
                    .scale(accuracy)
                    .outputQuality(accuracy)
                    .toOutputStream(outputStream);
                imageBytes = outputStream.toByteArray();
            }
            log.info("【图片压缩】imageId={} | 图片原大小={}kb | 压缩后大小={}kb",
                imageId, srcSize / KB_SIZE, imageBytes.length / KB_SIZE);

            return imageBytes;
        } catch (Exception e) {
            log.error("【图片压缩】msg=图片压缩失败! 返回原图片", e);
            return imageBytes;
        }
    }

    /**
     * 自动调节精度(经验数值)
     *
     * @param size 源图片大小
     * @return 图片压缩质量比
     */
    private static double getAccuracy(long size) {
        double accuracy;
        if (size < 900) {
            accuracy = 0.85;
        } else if (size < 2047) {
            accuracy = 0.6;
        } else if (size < 3275) {
            accuracy = 0.44;
        } else {
            accuracy = 0.4;
        }
        return accuracy;
    }
}
